import { getToken, setToken, removeToken } from '@/utils/auth'

import { reqLogin, reqGetProfile, reqGetBaseInfo } from '@/api/user'

const state = {
  token: getToken() || '', // token字符串
  userInfo: {}
}
const mutations = {
  // 设置token
  setToken(state, newToken) {
    state.token = newToken
    // cookies永久存储
    setToken(newToken)
  },
  // 删除token
  removeToken(state) {
    state.token = ''
    // 清除cooki里面的token
    removeToken()
  },
  // 设置用户信息
  setUserInfo(state, newUserInfo) {
    state.userInfo = newUserInfo
  },
  // 清空用户信息
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  // 登录成功获取token
  async login(context, data) {
    const res = await reqLogin(data)
    // console.log(res)
    //  res.data.data 响应拦截器解构了一层 => res.data
    context.commit('setToken', res.data)
  },
  // 获取用户信息
  async getUserInfo(context) {
    const res1 = await reqGetProfile()
    const res2 = await reqGetBaseInfo(res1.data.userId)
    // console.log(res1, res2, 111)
    const res = { ...res1.data, ...res2.data }
    // console.log(res)
    context.commit('setUserInfo', res)

    // 返回用户信息
    return res
  },
  // 退出登录
  logout(context) {
    context.commit('removeToken')
    context.commit('removeUserInfo')
  }
}
const getters = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
